package com.sp.scmdb.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sp.scmdb.bean.ViolationRecordBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.common.action.BaseAction;
import com.sp.scmdb.entity.Employee;
import com.sp.scmdb.entity.FileUpload;
import com.sp.scmdb.entity.User;
import com.sp.scmdb.service.EmployeeService;
import com.sp.scmdb.service.FileUploadService;
import com.sp.scmdb.service.ViolationRecordService;
import com.sp.scmdb.utils.HibernateUUID;

@Controller("violationRecordAction")
@Scope("prototype")
public class ViolationRecordAction extends BaseAction<ViolationRecordBean> {

	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(ViolationRecordAction.class);
	
	private ViolationRecordService violationRecordService;
	private EmployeeService employeeService;
	private FileUploadService fileUploadService; 

	@Autowired
	public void setViolationRecordService(ViolationRecordService violationRecordService) {
		this.violationRecordService = violationRecordService;
	}
	
	@Autowired
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	@Autowired
	public void setFileUploadService(FileUploadService fileUploadService) {
		this.fileUploadService = fileUploadService;
	}

	public String findAll() {
		try {
			List<ViolationRecordBean> vrList = violationRecordService.getListViolationRecord(null);
			entity.setAllList(vrList);
			entity.setList(vrList.subList(entity.getCurrentRow(), entity.getLastRow()));
			
			this.button("Super.Popup(5,'添加','/SCMDB/violationRecordAction!newViolationRecord.action','',610,560)",
					"Super.editData('/SCMDB/violationRecordAction!findViolationRecord.action?id=',610,560)",
					"Super.delData('/SCMDB/violationRecordAction!delViolationRecord.action?pId=')");
		} catch (Exception e) {
			log.error("findAll fail!reason:" + e.getMessage());
			return "fail";
		}
		return SUCCESS;
	}
	
	public String newViolationRecord() {
		return "newSucc";
	}
	
	public String findViolationRecord() {
		try {
			String pid = request.getParameter("id");
			entity = violationRecordService.getViolationRecord(pid);
			
			return "editSucc";
		} catch (Exception e) {
			log.error("find securityTraining failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	
	public String editViolationRecord() {
		try {
			User user = (User)session.get(CommonParamter.USER_ENTITY);
			fileUpload(entity.getAttachmentId(), user);
			
			Employee employee = employeeService.getById(entity.getEmployee().getId().toString());
			entity.setEmployee(employee);
			
			String[] illegalTypeIds = request.getParameterValues("illegalTypeIds");
			
			String strPeccancys = employee.getPeccancys();
			if(StringUtils.isEmpty(strPeccancys)) {
				strPeccancys = "0";
			}
			employee.setPeccancys(String.valueOf((Integer.parseInt(strPeccancys) + 1)));
			employeeService.editEmployee(employee);
			
			if(illegalTypeIds != null) {
				String str = "";
				for(int i = 0; i < illegalTypeIds.length; i++) {
					str += illegalTypeIds[i] + ",";
				}
				str = str.substring(0, str.length() - 1);
				entity.setIllegalType(str);
			}
			
			String result = violationRecordService.editViolationRecord(entity);
			messageSession(result, "违章记录");
			return "commitSucc";
		} catch (Exception e) {
			log.error("edit securityTraining failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	
	public String delViolationRecord() {
		String flg = null;
		try {
			String pId = request.getParameter("pId");
			if (StringUtils.isNotEmpty(pId)) {
				String[] arr = pId.split(",");
				flg = violationRecordService.delViolationRecord(arr);
			}
			
			messageSession(flg, "违章记录");
			log.info("delete suncce");
			return "commitSucc";
		} catch (Exception e) {
			log.error("delete violationRecord fail" + e.getMessage());
			return "fail";
		}		
	}
	
	public String addViolationRecord() {
		
		try {
			User user = (User)session.get(CommonParamter.USER_ENTITY);
			
			String attachmentId = HibernateUUID.generateUUID();
			fileUpload(attachmentId, user);
			
			String empId = request.getParameter("empId");
			String[] illegalTypeIds = request.getParameterValues("illegalTypeIds");
			
			Employee employee = employeeService.getById(empId);
			String strPeccancys = employee.getPeccancys();
			if(StringUtils.isEmpty(strPeccancys)) {
				strPeccancys = "0";
			}
			employee.setPeccancys(String.valueOf((Integer.parseInt(strPeccancys) + 1)));
			employeeService.editEmployee(employee);
			
			entity.setEmployee(employee);
			entity.setCreatedDate(new DateTime());
			entity.setUser(user);
			if(illegalTypeIds != null) {
				String str = "";
				for(int i = 0; i < illegalTypeIds.length; i++) {
					str += illegalTypeIds[i] + ",";
				}
				str = str.substring(0, str.length() - 1);
				entity.setIllegalType(str);
			}
			entity.setAttachmentId(attachmentId);
			
			String result = violationRecordService.createViolationRecord(entity);
			messageSession(result, "违章记录");
			
			//return SUCCESS;
			return "commitSucc";
		} catch (Exception e) {
			log.error("add violationRecord failed! reason:" + e.getMessage());
			return "fail";
		}
	}
	
	private boolean fileUpload(String attachmentId, User user) {
		boolean upload = false;
		try {
			File mkFile = new File(getSavePath());
			if(!mkFile.exists()) mkFile.mkdir();
			
			List<File> files = getImage();
			if (files != null && files.size() > 0) {
	            for (int i = 0; i < files.size(); i++) {
	            	
	            	//插入数据库记录
	                FileUpload fileUpload = new FileUpload();
	                fileUpload.setSysId(HibernateUUID.generateUUID());
	                
	            	FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + fileUpload.getSysId() + getExtention(imageFileName.get(i)));
	            	FileInputStream fis = new FileInputStream(files.get(i));
	                byte[] buffer = new byte[1024];
	                int len = 0;
	                while ((len = fis.read(buffer)) > 0) {
	                    fos.write(buffer, 0, len);
	                }
	                fis.close();
	                fos.close();
	                
	                //插入数据库记录
	                fileUpload.setEntityId(attachmentId);
	                fileUpload.setUser(user);
	                fileUpload.setUploadType("violationRecord");
	                fileUpload.setContentType(imageContentType.get(i));
	                fileUpload.setFileSize(files.get(i).length());
	                fileUpload.setName(imageFileName.get(i));
	                fileUpload.setPath(getSavePath() + "\\");
	                fileUpload.setUploadName(fileUpload.getSysId() + getExtention(imageFileName.get(i)));
	                fileUpload.setCreatedDate(new Date());
	                fileUploadService.createFileUpload(fileUpload);
	            }
	        }
			
			upload = true;
			log.error("upload file success!");
		} catch (Exception e) {
			log.error("upload file failed! reason:" + e.getMessage());
		}
		
		return upload;
	}
	
	private List<File> image; // 上传的文件
    private List<String> imageFileName; // 文件名称
    private List<String> imageContentType; // 文件类型
    private String savePath;

	public List<File> getImage() {
		return image;
	}

	public void setImage(List<File> image) {
		this.image = image;
	}

	public List<String> getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(List<String> imageFileName) {
		this.imageFileName = imageFileName;
	}

	public List<String> getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(List<String> imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	private String getExtention(String fileName)  {
        int pos = fileName.lastIndexOf( "." );
        return fileName.substring(pos);
   } 

}
